import 'dart:convert' show json;
import 'package:flutter/foundation.dart';

class WechatUserinfoModel {
  WechatUserinfoModel({
    this.openid,
    this.nickname,
    this.sex,
    this.province,
    this.city,
    this.country,
    this.headimgurl,
    this.privilege,
    this.unionid,
  });

  factory WechatUserinfoModel.fromJson(Map<String, dynamic> jsonRes) {
    if (jsonRes == null) {
      return null;
    }

    final List<String> privilege =
        jsonRes['privilege'] is List ? <String>[] : null;
    if (privilege != null) {
      for (final dynamic item in jsonRes['privilege']) {
        if (item != null) {
          tryCatch(() {
            privilege.add(asT<String>(item));
          });
        }
      }
    }
    return WechatUserinfoModel(
      openid: asT<String>(jsonRes['openid']),
      nickname: asT<String>(jsonRes['nickname']),
      sex: asT<int>(jsonRes['sex']),
      province: asT<String>(jsonRes['province']),
      city: asT<String>(jsonRes['city']),
      country: asT<String>(jsonRes['country']),
      headimgurl: asT<String>(jsonRes['headimgurl']),
      privilege: privilege,
      unionid: asT<String>(jsonRes['unionid']),
    );
  }

  String openid;
  String nickname;
  int sex;
  String province;
  String city;
  String country;
  String headimgurl;
  List<String> privilege;
  String unionid;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'openid': openid,
        'nickname': nickname,
        'sex': sex,
        'province': province,
        'city': city,
        'country': country,
        'headimgurl': headimgurl,
        'privilege': privilege,
        'unionid': unionid,
      };
  @override
  String toString() {
    return json.encode(this);
  }
}

void tryCatch(Function f) {
  try {
    f?.call();
  } catch (e, stack) {
    debugPrint('$e');
    debugPrint('$stack');
  }
}

T asT<T>(dynamic value) {
  if (value is T) {
    return value;
  }
  if (value != null) {
    final String valueS = value.toString();
    if (0 is T) {
      return int.tryParse(valueS) as T;
    } else if (0.0 is T) {
      return double.tryParse(valueS) as T;
    } else if ('' is T) {
      return valueS as T;
    } else if (false is T) {
      if (valueS == '0' || valueS == '1') {
        return (valueS == '1') as T;
      }
      return bool.fromEnvironment(value.toString()) as T;
    }
  }
  return null;
}
